package DMSXL._2024.TX;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Map;

public class largestSumAfterKNegations {
    public static void main(String[] args) {
        int[] nums = {-8,3,-5,-3,-5,-2};
        System.out.println(new largestSumAfterKNegations().largestSumAfterKNegations(nums,6));
    }
    public int largestSumAfterKNegations(int[] nums, int k) {
        int result = 0;
        Arrays.sort(nums);
        int index = 0;
        //尽可能把最小的负数变为正数。
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] < 0 && k > 0){
                index++;
                k--;
                nums[i] = - nums[i];
                result += nums[i];
            }
        }
        //如果k为0，说明都在变化负数
        for (int i = index; i < nums.length; i++) {
            result += nums[i];
        }
        if(k == 0){
            return result;
        }else {
            if(k % 2 == 0){
                return result;
            }else {
                Arrays.sort(nums);

                return result - 2 * nums[0];
            }
        }
    }
}
